package 面试题;

import com.sun.tools.javac.Main;

//只能有一个实例
//自行创建
//提供实例
public class 单例模式面试题 {
    public static void main(String[] args) {
        //获取饿汉对象
        Singleton1 singleton1 = Singleton1.SINGLETON_1;
        //获取枚举写法的饿汉
        Singleton2 singleton2 = Singleton2.SINGLETON_1;
        //获取懒汉式的对象
        Singleton4 singleton4 = Singleton4.getBean();

    }
}


//饿汉式，直接创建，不管你需不要要，不存在线程安全问题
class Singleton1{
    public static final Singleton1 SINGLETON_1 = new Singleton1();
}
//枚举写法,区别：返回的对象已重写toString方法
enum Singleton2{
    SINGLETON_1
}
//静态创建法
class Singleton3{
    public static final Singleton3 SINGLETON_3;
    static {
        //初始化xxx方法
        SINGLETON_3 = new Singleton3();
    }
}

//懒汉式，延迟创建,存在线程安全问题，只适合单线程
class Singleton4{
    private static Singleton4 singleton4;
    public static Singleton4 getBean(){
        //初始化xxx方法
        if (singleton4 == null){
            singleton4 = new Singleton4();
        }
        return singleton4;
    }
}
//线程安全版，使用同步对象锁，防止被多次创建
class Singleton5{
    private static Singleton5 singleton5;
    public static Singleton5 getBean(){
        //初始化xxx方法
        if (singleton5 == null){
            synchronized (Singleton5.class){
                if (singleton5 == null){
                    singleton5 = new Singleton5();
                }
            }
        }
        return singleton5;
    }
}
//内部类方法，线程安全，且效率更高，内部类不会因为外部类初始化而初始化
class Singleton6{

    private static class Inner{
        private static final Singleton6 singleton6 = new Singleton6();
    }
    public static Singleton6 getBean(){
        return Inner.singleton6;
    }
}